const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MinCssExtractPlugin = require('mini-css-extract-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const serverConfig = require('./server.js')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const webpack = require('webpack')
const HappyPack = require('happypack')
const DvaAutoRouterPlugin = require('./plugin/DvaAutoRouterPlugin')


const merge = (isUse , conf) => {
    if(isUse === false) {
        return []
    }
    return [conf]
}

const arr2obj = (arr , visitFunc) => {
    let r = {}
    arr.forEach(v => {
        r[v] = visitFunc(v)
    })
    return r
}

const Webpack = require('webpack')
module.exports = {
    devServer :{
        port : serverConfig.port,
        progress: true,
        contentBase : `./${serverConfig.path}`,
        //open : true,
        compress : true,
        proxy: serverConfig.proxy,
        hot:true,
    },
    mode : process.env.ENV,
    // [index] => {index : './src/index.js'}
    entry : arr2obj(serverConfig.entry,v => `./src/${v}.js`),
    devtool : 'eval-source-map',
    resolve : serverConfig.resolve,
    output : {
        filename : '[name].[hash:8].js',
        path: path.resolve(__dirname,serverConfig.path),
        publicPath: serverConfig.publicPath
    },
    plugins:[
        // new DvaAutoPlugin({

        // }),
        ...serverConfig.entry.map(v => new HtmlWebpackPlugin({
            template : `./src/${v}.html`,
            filename : `${v}.html`,
            minify:{
                removeAttributeQuotes:true,
                collapseInlineTagWhitespace:true,
            },
            chunks: [v],
        })),
        new MinCssExtractPlugin({
            filename : 'css/[name].[hash:10].css'
        }),
        new Webpack.ProvidePlugin({
            // $ : 'jquery'
        }),
        new Webpack.DefinePlugin({
            ENV : JSON.stringify(process.env.ENV)
        }),
        new CleanWebpackPlugin({
            cleanOnceBeforeBuildPatterns:[
                '*.js',
                'css/*'
            ]
        }),
        new webpack.DllReferencePlugin({
            manifest: path.resolve(__dirname,serverConfig.path,'dll','react.manifest.json')
        }),
        new HappyPack({ //多线程打包
            id: 'js',
            use: [{
                loader: 'babel-loader',
                options: {
                    presets: [
                        '@babel/preset-env','@babel/preset-react'
                    ],
                    plugins:[
                        ['@babel/plugin-proposal-decorators',{legacy:true}],
                        ['@babel/plugin-proposal-class-properties',{loose : true}],
                        '@babel/plugin-transform-runtime',
                        '@babel/plugin-syntax-dynamic-import'
                    ]
                }
            }]
        }),
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin(),
    ],
    externals : { // 不需要打包的模块
        jquery : '$'
    },
    resolve: serverConfig.resolve,
    module : {
        rules:[
            ...merge(serverConfig.eslint,{
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader:'eslint-loader',
                    options :{
                        enforce : 'pre'
                    }
                },
            }),
            {
                test: /\.(htm|html)$/i,
                loader: 'html-withimg-loader'
            },
            {
                test : /\.(png|jp?g|gif|svg)$/i,
                use: [
                    {
                      loader: 'url-loader',
                      options: {
                        outputPath: 'images',
                        limit: 2048,
                      },
                    },
                  ],
            },
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                include:path.resolve(__dirname,'src'),
                use : 'happypack/loader?id=js',
            },
            {
                test: /\.css$/,
                use:[MinCssExtractPlugin.loader,'css-loader','postcss-loader']
            },
            {
                test : /\.less$/,
                //use : 'happypack/loader?id=less',
                use : [
                    MinCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader',
                    'less-loader'
                ]
            }
        ]
    },
    optimization:{
        minimizer:[
            new UglifyJsPlugin({
                cache:true,
                parallel : true,
                sourceMap : true,
            }),
            new OptimizeCSSAssetsPlugin(),
        ],
        splitChunks:{
            cacheGroups:{
                vendor: {
                    test: /node_modules/,
                    priority: 1,
                    chunks: 'initial',
                    maxSize: 0,
                    minChunks: 2,
                },
            }
        }
    }
}
